package 力扣;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 给定二叉树 [3,9,20,null,null,15,7],

 3
 / \
 9  20
 /  \
 15   7
 返回锯齿形层次遍历如下：

 [
 [3],
 [20,9],
 [15,7]
 ]
 */
public class _103二叉树的锯齿形层次遍历 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        if( root == null ) return new ArrayList<List<Integer>>();
        LinkedList<TreeNode> quque = new LinkedList<>();
        ArrayList<List<Integer>> lists = new ArrayList<>();
        quque.add(root);
        boolean flag = false;
        while( !quque.isEmpty()){
            // 获取改层的节点数
            int size = quque.size();
            List<Integer> list = new ArrayList<Integer>();
            while( size > 0 ){
                TreeNode node = quque.poll();
                if (flag) { //往前添加数据
                    list.add(0, node.val);
                } else {
                    list.add(node.val);
                }
                if( node.left != null ){
                    quque.add(node.left);
                }
                if( node.right != null ){
                    quque.add(node.right);
                }
                size--;
            }

            flag = !flag;

            lists.add(list);
        }

        return lists;
    }
}
